﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DocumentGeneration.Models;
using Microsoft.Office.Interop.Word;

namespace DocumentGeneration.Controllers
{
    public class AssignmentController : Controller
    {
        /// <summary>
        /// GET: /Assignment/
        /// </summary>
        /// <returns>The requested view</returns>
        public ActionResult Index()
        {
            string action = Request.QueryString["action"];
            if (action == "Download")
            {
                generateDocument();
            }

            /* put the title of the screen in the view bag */
            ViewBag.Message = "Stageplan";

            /* get the assignment data */
            AssignmentModel Assignment = getAssignmentData();

            return View(Assignment);
        }

        [HttpPost]
        public ActionResult Download()
        {
            generateDocument();

            AssignmentModel Assignment = getAssignmentData();

            return View(Assignment);
        }

        /// <summary>
        /// GET: /Assignment/EditCompany
        /// </summary>
        /// <returns>The requested view</returns>
        public ActionResult Edit(string type)
        {
            /* get the assignment data */
            AssignmentModel assignment = getAssignmentData();

            /* set the title of the edit page */
            switch (type)
            {
                case "company":
                    ViewBag.Message = "Bedrijf wijzigen";
                    break;
                case "motive":
                    ViewBag.Message = "Aanleiding wijzigen";
                    break;
                case "problem":
                    ViewBag.Message = "Probleemstelling wijzigen";
                    break;
                case "objective":
                    ViewBag.Message = "Doelstelling van de opdracht wijzigen";
                    break;
                case "result":
                    ViewBag.Message = "Resultaat wijzigen";
                    break;
                case "baseline":
                    ViewBag.Message = "Uitgangssituatie wijzigen";
                    break;
                case "activities":
                    ViewBag.Message = "Werkzaamheden wijzigen";
                    break;
                case "risks":
                    ViewBag.Message = "Risico's en maatregelen wijzigen";
                    break;
                case "products":
                    ViewBag.Message = "Op te leveren (tussen)producten wijzigen";
                    break;
                default:
                    /* no type known */
                    return RedirectToAction("Index");
            }

            /* set the type in the viewbag */
            ViewBag.Type = type;

            return View(assignment);
        }

        /// <summary>
        /// Called when the user submits the edited data
        /// </summary>
        /// <param name="assignment">The model containing the changed data</param>
        /// <returns>Redirect or the view</returns>
        [HttpPost]
        public ActionResult Edit(AssignmentModel model, string type)
        {
            /* save the edited data */
            saveAssignmentData(model, type);

            return RedirectToAction("Index");
        }

        /// <summary>
        /// Called when assignment data needs to be fetched from the database
        /// </summary>
        /// <returns>Assignment model filled with database data</returns>
        private AssignmentModel getAssignmentData()
        {
            /* create a database connection */
            AfstudeerregistratieDataContext database = new AfstudeerregistratieDataContext();

            /* create an assignment to hold the returned assignment data */
            AssignmentModel assignment = new AssignmentModel();

            /* request the assignment data */
            IEnumerable<Assignment> assignments = 
                from dbAssignment in database.Assignments
                where dbAssignment.Student.Equals("09006117")
                select dbAssignment;

            /* enter the fetched data into the temp assignment */
            if (assignments.Count() > 0)
            {
                //set the model values
                assignment.Name = assignments.First().Company1.Name;
                assignment.Address = assignments.First().Company1.Address;
                assignment.Postcode = assignments.First().Company1.Postcode;
                assignment.City = assignments.First().Company1.City;
                assignment.TelephoneNumber = assignments.First().Company1.TelephoneNumber;
                assignment.ContactPerson = assignments.First().Company1.ContactPerson;
                assignment.Email = assignments.First().Company1.Email;
                assignment.Motive = assignments.First().Motive;
                assignment.ProblemDefinition = assignments.First().ProblemDefinition;
                assignment.Objective = assignments.First().Objective;
                assignment.Result = assignments.First().Result;
                assignment.Baseline = assignments.First().Baseline;
                assignment.Activities = assignments.First().Activities;
                assignment.RisksAndMeasures = assignments.First().RisksAndMeasures;
                assignment.Products = assignments.First().Products;
                assignment.Student = assignments.First().Student;
            }
            else
            {
                /* no row found */
                return null;
            }

            return assignment;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="model"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private ActionResult saveAssignmentData(AssignmentModel model, string type)
        {
            /* if the model is valid */
            if (ModelState.IsValid && type != "")
            {
                AfstudeerregistratieDataContext database = new AfstudeerregistratieDataContext();  
                Assignment assignment = database.Assignments.Single(myAssignment => myAssignment.Student == "09006117");

                /* get the right data depending on the type edited */
                switch (type)
                {
                    case "company":
                        assignment.Company1.Name = model.Name;
                        assignment.Company1.Address = model.Address;
                        assignment.Company1.Postcode = model.Postcode;
                        assignment.Company1.City = model.City;
                        assignment.Company1.TelephoneNumber = model.TelephoneNumber;
                        assignment.Company1.ContactPerson = model.ContactPerson;
                        assignment.Company1.Email = model.Email;
                        break;
                    case "motive":
                        assignment.Motive = model.Motive;
                        break;
                    case "problem":
                        assignment.ProblemDefinition = model.ProblemDefinition;
                        break;
                    case "objective":
                        assignment.Objective = model.Objective;
                        break;
                    case "result":
                        assignment.Result = model.Result;
                        break;
                    case "baseline":
                        assignment.Baseline = model.Baseline;
                        break;
                    case "activities":
                        assignment.Activities = model.Activities;
                        break;
                    case "risks":
                        assignment.RisksAndMeasures = model.RisksAndMeasures;
                        break;
                    case "products":
                        assignment.Products = model.Products;
                        break;
                }

                try 
                {
                    /* submit changes */
                    database.SubmitChanges();
                    return RedirectToAction("Index");
                }
                catch(Exception e) 
                {
                    ViewBag.QueryStatus = e;
                }
            }

            return View();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ActionResult generateDocument()
        {
            /* get the assignment */
            AssignmentModel assignment = getAssignmentData();

            /* set objects */
            Object templateName = "C:\\Users\\Leon\\Documents\\Projects\\Afstudeerregistratie\\Afstudeerregistratie\\DocumentGeneration\\Content\\Templates\\Afstudeerplan.doc";
            Object missing = System.Reflection.Missing.Value;
            Object saveName = "C:\\Users\\Leon\\Desktop\\Afstudeerplan-" + assignment.Student + ".doc";
            Object vFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument97;
            Object titleBookmark = "AfstudeerOpdracht";
            Object companyBookmark = "Bedrijf";
            Object motiveBookmark = "Aanleiding";
            Object problemBookmark = "Probleemstelling";
            Object objectiveBookmark = "Doelstelling";
            Object resultBookmark = "Resultaat";
            Object baselineBookmark = "Uitgangsituatie";
            Object activitiesBookmark = "Werkzaamheden";
            Object risksBookmark = "RisicoEnMaatregelen";
            Object productsBookmark = "Producten";

            /* create a word application */
            Application app = new Application();

            try
            {
                /* open a document */
                Document document = app.Documents.Open(ref templateName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
            
                /* assign text to the bookmarks */
                document.Bookmarks.get_Item(ref titleBookmark).Range.Text = assignment.Name;
                document.Bookmarks.get_Item(ref companyBookmark).Range.Text = assignment.Name + "\r\n" + assignment.Address + "\r\n" + assignment.Postcode + "\r\n" + assignment.TelephoneNumber + "\r\n" + assignment.ContactPerson + "\r\n" + assignment.Email; 
                document.Bookmarks.get_Item(ref motiveBookmark).Range.Text = assignment.Motive;
                document.Bookmarks.get_Item(ref problemBookmark).Range.Text = assignment.ProblemDefinition;
                document.Bookmarks.get_Item(ref objectiveBookmark).Range.Text = assignment.Objective;
                document.Bookmarks.get_Item(ref resultBookmark).Range.Text = assignment.Result;
                document.Bookmarks.get_Item(ref baselineBookmark).Range.Text = assignment.Baseline;
                document.Bookmarks.get_Item(ref activitiesBookmark).Range.Text = assignment.Activities;
                document.Bookmarks.get_Item(ref risksBookmark).Range.Text = assignment.RisksAndMeasures;
                document.Bookmarks.get_Item(ref productsBookmark).Range.Text = assignment.Products;

                /* save file */
                document.SaveAs2(ref saveName, ref vFormat, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);

                /* close document and application */
                document.Close(ref missing, ref missing, ref missing);
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("Failed to create document: " + ex);
            }

            app.Quit(ref missing, ref missing, ref missing);

            return RedirectToAction("Index");
        }
    }
}
